using System;
using UnityEngine;

public class RankManager : MonoBehaviour
{
	[Serializable]
	public class EditorReferences
	{
		public RankParameters[] ranks;
	}

	[Serializable]
	public class RankParameters
	{
		public Sprite icon;

		public Color mainColor;

		public int xpRequired;
	}

	public static RankManager Instance;

	[SerializeField]
	public EditorReferences references = new EditorReferences();

	private int _cachedRank;

	private int _cachedXp;

	private int _xpReward;

	public int CachedRank => _cachedRank;

	public int CachedXp => _cachedXp;

	public int XpReward => _xpReward;

	private void Awake()
	{
		if (Instance == null)
		{
			Instance = this;
			UnityEngine.Object.DontDestroyOnLoad(base.gameObject);
			CalculatePlayerRank();
		}
		else
		{
			UnityEngine.Object.Destroy(base.gameObject);
		}
	}

	private void CalculatePlayerRank()
	{
		_cachedXp = PlayerData.Instance.Xp;
		_cachedRank = 1;
		for (int i = 1; i < references.ranks.Length; i++)
		{
			if (_cachedXp >= references.ranks[i].xpRequired)
			{
				_cachedXp -= references.ranks[i].xpRequired;
				_cachedRank++;
			}
		}
		if (_cachedXp >= references.ranks[references.ranks.Length - 1].xpRequired)
		{
			int xpRequired = references.ranks[references.ranks.Length - 1].xpRequired;
			int num = Mathf.FloorToInt((float)_cachedXp / (float)xpRequired);
			_cachedRank = references.ranks.Length + num;
			_cachedXp -= xpRequired * num;
		}
		AchievementManager.Instance.SetPersistentData(AchievementKeys.Rank, _cachedRank);
	}

	public RankParameters GetRankParameters(int rank)
	{
		rank = Mathf.Clamp(rank, 0, references.ranks.Length - 1);
		return references.ranks[rank];
	}

	public void AddXpReward(int reward)
	{
		_xpReward += reward;
		PlayerData.Instance.Xp += reward;
		PlayerData.Instance.SaveData();
	}

	public void CashInXpReward()
	{
		_xpReward = 0;
		CalculatePlayerRank();
	}
}
